<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="m-table">
      <template #form="{ form }">
        <XForm style="padding: 16px 8px 8px" :fieldList="fieldList" :options="formOption" :formData="form" v-if="formShow" :originOption="originOption">
          <template #ShopCascade>
            <SelectsShopCascade v-model:platform="form.platform_id" v-model:site="form.site_id" v-model:shop="form.shop_id" />
          </template>
          <template #reason>
            <ReasonCascade :info="form" :firstOption="firstOption" />
          </template>

          <template #RecipientCountry>
            <SelectCountry placeholder="收件国家" multiple collapseTags labelKey2="true" v-model:modelValue="form.recipient_country_id" style="width: 200px" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="addVisible = true" v-hasPermi="[userAuthList.refund.add]"> 添加退款 </el-button>
        <el-button type="primary" @click="handleBatchApproval" v-hasPermi="[userAuthList.refund.batchAudit]"> 批量审核 </el-button>
        <el-button @click="onRefundRequest" v-hasPermi="[userAuthList.refund.batchApi]">批量API退款</el-button>

        <el-button @click="onCancelRefund" v-hasPermi="[userAuthList.refund.cancelRefund]">取消退款</el-button>

        <span class="m-[auto] text-[#333] mr-[8px]">总退款金额: {{ amountData.amount }} RMB {{ amountData.amountUsd }} USD</span>
        <el-dropdown v-hasPermi="[userAuthList.refund.export]">
          <el-button> 导出 <span class="dk-iconfont icon-Download"></span> </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="importHandleClick(1)">导出退款SKU明细</el-dropdown-item>
              <el-dropdown-item @click="importHandleClick(2)">导出退款订单明细</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="openDialogImport" v-hasPermi="[userAuthList.refund.import]"> 导入 </el-button>
        <el-button @click="visible = true" v-hasPermi="[userAuthList.refund.reason]"> 退款原因管理 </el-button>
      </template>

      <template #GoodsSlot="{ row }">
        <ExpandList :show-expand="row?.products?.length > 1" :expand="row.expandStatus" @change="rendererView" :length="row?.products?.length">
          <template #default="{ expand }">
            <div class="product-item" v-for="(item, index) in getRows(row, expand)" :key="`${item.sku}${index}`">
              <div class="border-[var(--base-border-color)] border-[1px] rounded-[4px] p-[7px] text-[14px] relative leading-[20px] w-[378px]">
                <div>
                  <span class="text-[#3487ff] text-[14px] cursor-pointer" @click="onSku(item)">{{ item.sku }}</span>
                  <el-divider direction="vertical" />
                  <VText title="自定义SKU" :value="item.custom_sku" :line="2" />
                </div>
                <VText :value="item.sku_cn_title" :line="2" />

                <div class="absolute right-[0] top-[0]">
                  <span class="leading-[17px]"> {{ row.order_currency }} {{ item.original_price }} </span>
                  <span class="bg-[#EBECEE] text-[#FF0000] rounded-bl-[4px] px-[4px] ml-[4px]"> *{{ item.quantity }} </span>
                </div>
              </div>
            </div>
          </template>
        </ExpandList>
      </template>
    </VTable>
    <Log dialog v-model="logVisible" :autoLoad="false" tag="refund" :business_id="logId" />
    <!-- <AddRefund v-model="addVisible" :id="refundId" @close="handleClose" :disabled="refundDisabled" /> -->
    <!-- <ApprovalDialog v-model="approvalVisible" @refresh="handleRefresh" :rows="[{ id: refundId }]" /> -->

    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <RefundReason v-model="visible" @refreshList="refreshList" />
    <AddRefund ref="addRefund" v-model="addVisible" @refresh="handleRefresh" :id="refundId" :disabled="refundDisabled" @close="handleClose" />
    <!-- 审批 -->
    <ApprovalDialog v-model="approvalVisible" :rows="rows" @refresh="handleRefresh" />

    <DialogImport :download-url="downloadUrl" :call-back="importCallBack" tplName="退款单导入模板.xlsx" importUrl="import/order_refund/" v-if="visibleImport" ref="dialogImportRef" />
  </VPage>
</template>

<script setup lang="jsx">
import { refundRequest, getReasonList, refundReview, getOrderList } from "./api"
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"
import ReasonCascade from "./components/ReasonCascade/index.vue"

import RefundRecord from "@/views/user/list/detail/RefundRecord/index.vue"

import DerivedCenter from "@/components/DerivedCenter"
import RefundReason from "./components/RefundReason/index.vue"
import AddRefund from "./components/AddRefund/index.vue"
import ApprovalDialog from "@/views/user/list/detail/RefundRecord/ApprovalDialog/index.vue"

import { userAuthList } from "@/Auth/user.js"

import ExpandList from "@/components/ExpandList/index.vue"
import { isPermission } from "@/hooks/permission.js"

import SelectCountry from "@/components/Selects/SelectCountry/index.vue"
// const SelectCountryRef = ref()

import DialogImport from "./components/DialogImport/index.vue"
const visibleImport = ref(false)
const downloadUrl = ref("")
const dialogImportRef = ref()
const openDialogImport = () => {
  visibleImport.value = true
  nextTick(() => {
    dialogImportRef.value.open()
  })
}
const importParamsFormatter = (query) => {}

const importCallBack = ({ downloadUrl, fileName, ossUrl }) => {
  getList()
}

import Log from "@/components/Log/index.vue"
import { formOption, fieldList, tablecColumns, handleFunctions } from "./config.jsx"
const form = ref()
const formData = ref({})
const model = ref({})
const listRef = ref()
const visible = ref(false)
const addVisible = ref(false)

const affixRef = ref()
const amountData = ref({})
onActivated(() => {
  affixRef.value?.updateRoot()
})
const router = useRouter()
const addRefund = ref()
const firstOption = ref([])

// 导出中心
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let checkRow = tableRef?.value.$table.getCheckboxRecords()
  // console.log(listRef.value?.tableRef?.getCheckboxRecords());
  let condition = {}
  if (checkRow.length) {
    condition = { order_sn: checkRow.map((v) => v.order_sn) }
  } else {
    condition = tableRef?.value.getQueryForm()
    condition = getForm(condition)
  }
  // console.log(condition);
  // let condition = { ...formData.value }
  DerivedCenterRef.value.open({
    tag_name: e == 1 ? "order_refund_sku" : "order_refund",
    exportName: e == 1 ? "【订单退款管理】退款SKU明细导出" : "【订单退款管理】退款订单明细导出",
    condition,
  })
}

// 待优化
watch(
  () => router.currentRoute.value.query.form,
  (val) => {
    const { form, id } = router.currentRoute.value.query || {}
    if (form && id) {
      setTimeout(() => {
        addVisible.value = true
        setTimeout(() => {
          addRefund.value.noCombined.value = id
          addRefund.value.handleGetOrderInfo()
        }, 1000)
      }, 1000)
    }
  }
)
const refreshList = async () => {
  // 一级退款原因
  firstOption.value = (await getReasonList()).data.map((v) => ({
    ...v,
    label: `【${v.platform}】${v.reason}`,
    value: v.id,
  }))
}
import { getCurrency } from "@/api/public"
const originOption = ref({})
const formShow = ref(false)
onMounted(async () => {
  const { form, id } = router.currentRoute.value.query
  if (form && id) {
    setTimeout(() => {
      addVisible.value = true
      setTimeout(() => {
        addRefund.value.noCombined.value = id
        addRefund.value.handleGetOrderInfo()
      }, 1000)
    }, 1000)
  }
  // 一级退款原因
  firstOption.value = (await getReasonList()).data.map((v) => ({
    ...v,
    label: `【${v.platform}】${v.reason}`,
    value: v.id,
  }))
  nextTick(() => {
    handleFunctions.value = handleFunction.value
    tableRef?.value?.updateScroll()
    setTimeout(() => (formShow.value = true), 0)
  })

  originOption.value.countryOpt = (await getCurrency()).data.map((v) => ({ label: v.label, value: v.label }))
})

import action from "@/utils/action.js"
import ProductApi from "@/components/SelectProduct/api"
const onSku = (item) => {
  if (item.sku) {
    ProductApi.query({ sku: [item.sku] }).then((res) => {
      action.setGlobalState({
        changeMicoTabsPath: {
          path: "/goods/task/product/detail",
          type: "push",
          query: {
            type: "view",
            spuId: res.data?.[0].spu_id,
            sku: item.sku,
          },
        },
      })
    })
  }
}

const handleFunction = ref({
  // 跳转详情
  handleDetail: (order_sn) => {
    getOrderList({ query: [{ field: "order_sn", queryType: "terms", value: [order_sn] }] }).then((res) => {
      let id = res.data?.orders?.[0].id || ""
      id && router.push(`/user/list/detail?id=${id}`)
    })
  },
})
const approvalVisible = ref(false)
const rows = ref([])
// 批量审核
const handleBatchApproval = () => {
  const select = tableRef?.value.$table.getCheckboxRecords()
  if (!select.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  rows.value = select
  approvalVisible.value = true
}
// 审批
const handleApproval = (item) => {
  rows.value = [{ id: item.id }]
  approvalVisible.value = true
}

// 批量API退款
const onRefundRequest = () => {
  const select = tableRef?.value.$table.getCheckboxRecords()
  if (!select.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  ElMessageBox.confirm(`API退款${select.length}条订单？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      refundRequest({ ids: select.map((v) => v.id) }).then((res) => {
        ElMessage({ type: "success", message: "操作成功" })
        // tableRef?.value.query()
        getList()
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消操作" })
    })
}
// 取消退款
const onCancelRefund = () => {
  const select = tableRef?.value.$table.getCheckboxRecords()
  if (!select.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  ElMessageBox.confirm(`确定取消退款${select.length}条订单？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        refund_status: 3,
        ids: select.map((v) => v.id),
      }
      refundReview(params).then((res) => {
        ElMessage({ type: "success", message: "操作成功" })
        // tableRef?.value.query()
        getList()
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消操作" })
    })
}

// 刷新列表
const handleRefresh = () => {
  rows.value = []
  refundId.value = ""
  refundDisabled.value = false
  // tableRef?.value.query()
  getList()
}

const getList = async () => {
  // tableRef?.value.query()
  let rowsId = tableRef?.value.$table.getCheckboxRecords()?.map((v) => v.id)
  await tableRef?.value.query()
  let rows = tableRef?.value.$table.getData().filter((v) => rowsId.includes(v.id))
  tableRef?.value.$table.setCheckboxRow(rows, true)
  // nextTick(() => {
  //   checkboxChange()
  // })
}

defineExpose({ form })

const tableRef = ref()
// 渲染表格列
const rendererView = (e) => {
  // console.log(tableOptions.columns)
  // console.log(tableRef?.value?.initColumn(tableOptions.columns));
  // tableRef?.value?.$table.loadColumn(tableRef?.value?.initColumn(tableOptions.columns))
  // tableRef?.value?.$table.loadColumn(tableOptions.columns)
}
const getRows = (rows, expand) => {
  rows.expandStatus = expand
  const { products = [] } = rows || {}
  if (expand) return products
  if (!products?.length) return []
  if (products.length > 0 && products.length < 1) {
    return products
  }
  if (!expand) {
    return products?.slice(0, 1)
  }
}
const rowStyle = ({ row, column }) => {
  return { height: `${row?.expandStatus ? row.products.length * 110 : 130}px` }
}
import api from "@/views/user/list/api/index.js"
const tableOptions = reactive({
  formConfig: {
    save: "/oms/user/refund", // 必填，唯一
    data: {
      refund_status: "",
      // order_currency: "CNY",
      no: { type: "order_sn", value: "" },
      skuRange: { type: "sku", value: "" },
      noRange: { type: "order_sn", value: "" },
      timeRange: { type: "apply_at", value: "" },
      create_user: { type: "create_user", value: "" },
    },
  },
  rowConfig: {
    keyField: "id",
  },
  showOverflow: true,

  cellStyle: rowStyle,
  columns: [],
  scrollY: { enabled: false },
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        let param = { ...page, ...form }
        return getTab(param)
      },
    },
  },
})
const handleColumn = {
  title: "操作",
  width: 100,
  fixed: "right",
  slots: {
    default: ({ row }) => {
      return (
        <div>
          {isPermission([userAuthList.refund.details]) && (
            <el-button onClick={() => handleDetail(row)} link type="primary">
              详情
            </el-button>
          )}

          {+row.refund_status === 0 && isPermission([userAuthList.refund.edit]) && (
            <el-button link type="primary" onClick={() => handleEdit(row)}>
              编辑
            </el-button>
          )}
          <div class="mt-[6px]">
            {+row.refund_status === 0 && isPermission([userAuthList.refund.audit]) && (
              <el-button link type="primary" onClick={() => handleApproval(row)}>
                审批
              </el-button>
            )}

            {isPermission([userAuthList.refund.log]) && (
              <el-button link type="primary" onClick={() => handleLog(row)}>
                日志
              </el-button>
            )}
          </div>
        </div>
      )
    },
  },
}
tableOptions.columns = [{ fixed: "left", type: "checkbox", width: 50 }, ...tablecColumns.value, handleColumn]

import { getRefundList } from "../list/detail/api/index"
const getTab = async (param) => {
  let res = await getRefundList(getForm(param))
  if (res.data.refunds) {
    amountData.value.amount = res.data?.amount
    amountData.value.amountUsd = res.data?.amountUsd
    // API退款 默认值
    res.data.refunds.forEach((item) => {
      item.api_refund_status = ["ebay", "amazon"].includes(item.platform) ? "是" : "否"
    })
    res.data = res.data.refunds
  }
  tableRef?.value?.$table.reloadData([])
  return res
}

const getForm = (params) => {
  params.refund_amount = params.refund_amount?.min ? [params.refund_amount?.min, params.refund_amount?.max] : []
  for (const key in params) {
    if (params[key]?.value || params[key]?.key || params[key] == undefined) {
      delete params[key]
    }
  }
  let keys = ["sku", "custom_sku", "platform_sku", "spu", "asin", "sku_cn_title", "order_sn", "platform_order_sn", "buyer_name"]
  keys.forEach((key) => {
    params[key] = params[key]?.split("\n")?.filter((v) => !!v.trim())
    params[key] = params[key]?.map((v) => v.trim())
  })

  if (params.refund_amount.find(Boolean) == undefined) {
    delete params.refund_amount
  }
  // if (params?.platform_id) {
  //   params.platform_id = [params?.platform_id]
  // }
  return params
}

// 详情 编辑
const refundId = ref("")
const refundDisabled = ref(false)
const handleDetail = (item) => {
  refundDisabled.value = true
  refundId.value = item.id
  addVisible.value = true
}
const handleEdit = (item) => {
  refundId.value = item.id
  addVisible.value = true
}
const handleClose = () => {
  refundId.value = ""
  refundDisabled.value = false
}

// 日志
const logVisible = ref(false)
const logId = ref("")
const handleLog = (item) => {
  logId.value = item.id
  logVisible.value = true
}
</script>
<style lang="scss" scoped>
.m-table {
  :deep(.vxe-cell) {
    max-height: 100% !important;
    overflow: visible !important;
  }
}
</style>
